<script setup>
import { ref, onMounted, watch } from 'vue'
import { saveGoods, fetchGoodsTypeList } from '@/api/goods'
import { ElMessage } from 'element-plus'
import logger from '@/utils/logger'
import { fetchXjqhTree } from '@/api/xjqh'
import { generalFileUpload } from '@/api/upload'
import RichTextEditor from '@/components/RichTextEditor.vue'
import ViewHTML from '@/components/ViewHTML.vue'

const props = defineProps({
  initialData: {
    type: Object,
    default: null,
  },
})

const emit = defineEmits(['success', 'close'])

// 行政区划树
const xzqhTree = ref([])
const xzqhLoading = ref(false)
const selectedXzqh = ref([]) // 存储级联选择器选中的值
const goodsTypeOptions = ref([])
const goodsTypeLoading = ref(false)
const richTextVisible = ref(false)
const richTextContent = ref('')
const previewHtmlVisible = ref(false)
const uploadRef = ref(null)

// 获取行政区划树数据
const handleFetchXzqhTree = async () => {
  try {
    xzqhLoading.value = true
    const res = await fetchXjqhTree()
    if (res.code === 200) {
      xzqhTree.value = res.data || []
    }
  } catch (error) {
    logger.error('获取行政区划树数据失败', error)
    // 不显示错误提示，避免影响用户体验，但记录日志
  } finally {
    xzqhLoading.value = false
  }
}

const formRef = ref(null)
const formData = ref({
  dealerGoodsId: '', // 编辑需要
  dealerGoodsTypeId: '', // 商品类型
  dealerGoodsTypeName: '', // 商品类型名称
  cdXzqhId: '', // 商品专属区域id 其实就是行政区划
  isDiscontinued: 0, // 是否停售 0-否 1-是
  goodsName: '', // 商品名称
  goodsPicture: '', // 商品图片
  specifications: '', // 商品规格
  unit: '', // 商品单位
  introduce: '', // 富文本编辑器
  address: '', // 详细产地
})

// 监听级联选择器的变化
const handleXzqhChange = (value) => {
  if (value && value.length > 0) {
    // 获取最后一级的ID (区县级)
    formData.value.cdXzqhId = value[value.length - 1]
  } else {
    formData.value.cdXzqhId = ''
  }
  formRef.value?.validateField('cdXzqhId')
}

// 根据初始数据设置级联选择器的值
const setInitialXzqh = () => {
  const xzqhId = formData.value.cdXzqhId
  if (xzqhId) {
    // 根据区域ID回溯获取完整的路径数组
    const path = findXzqhPath(xzqhId, xzqhTree.value)
    if (path && path.length > 0) {
      selectedXzqh.value = path
    }
  }
}

// 递归查找从根节点到目标节点的路径
const findXzqhPath = (targetId, tree, currentPath = []) => {
  if (!tree || !tree.length) return null

  for (const node of tree) {
    // 尝试当前节点
    const newPath = [...currentPath, node.id]

    if (node.id === targetId) {
      return newPath
    }

    // 如果有子节点，继续递归查找
    if (node.children && node.children.length > 0) {
      const foundPath = findXzqhPath(targetId, node.children, newPath)
      if (foundPath) return foundPath
    }
  }

  return null
}

const rules = {
  goodsName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  dealerGoodsTypeId: [{ required: true, message: '请选择商品类别', trigger: 'change' }],
  specifications: [{ required: true, message: '请输入商品规格', trigger: 'blur' }],
  unit: [{ required: true, message: '请输入商品单位', trigger: 'blur' }],
  introduce: [{ required: true, message: '请输入商品介绍', trigger: 'change' }],
  goodsPicture: [{ required: true, message: '请上传商品图片', trigger: 'change' }],
  cdXzqhId: [{ required: true, message: '请选择积分消费区域', trigger: 'change' }],
}

const loading = ref(false)
const uploadLoading = ref(false)

// 处理图片上传
const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    formData.value.goodsPicture = res.data
    ElMessage.success('图片上传成功')
    formRef.value?.validateField('goodsPicture')
  } else {
    ElMessage.error(res.msg || '图片上传失败')
    if (uploadRef.value) {
      uploadRef.value.clearFiles()
    }
  }
  uploadLoading.value = false
}

// 处理图片上传失败
const handleUploadError = () => {
  ElMessage.error('图片上传失败')
  uploadLoading.value = false
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 处理文件超出限制
const handleExceed = () => {
  ElMessage.warning('只能上传1张图片')
}

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  uploadLoading.value = true
  return true
}

// 自定义上传方法
const customUpload = async (options) => {
  try {
    const res = await generalFileUpload(options.file)
    options.onSuccess(res)
  } catch (error) {
    options.onError(error)
  }
}

// 添加一个删除图片的方法
const clearUploadedImage = () => {
  formData.value.goodsPicture = ''
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
  ElMessage.success('图片已清除')
  formRef.value?.validateField('goodsPicture')
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 准备提交数据，清理不必要的临时状态
        const res = await saveGoods(formData.value)
        if (res.success) {
          ElMessage.success(props.initialData ? '修改成功' : '添加成功')
          emit('success')
          emit('close')
        } else {
          ElMessage.error(res.msg || '操作失败')
        }
      } catch (error) {
        logger.error('保存商品失败', error)
        ElMessage.error('操作失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 当xzqhTree数据加载后设置初始选中
watch(
  () => xzqhTree.value,
  (newVal) => {
    if (newVal && newVal.length > 0 && formData.value.cdXzqhId) {
      setInitialXzqh()
    }
  },
  { deep: true },
)

watch(
  () => formData.value.dealerGoodsTypeId,
  (val) => {
    const found = goodsTypeOptions.value.find((t) => t.dealerGoodsTypeId === val)
    if (found) {
      formData.value.dealerGoodsTypeName = found.dealerGoodsTypeName
    }
  },
)

// 远程搜索方法
const remoteSearchGoodsTypes = async (query) => {
  goodsTypeLoading.value = true
  try {
    const params = {
      currentPage: 1,
      pageSize: 9999,
      queryFields: {
        goodsTypeName: query ? query.trim() : null,
      },
    }
    const res = await fetchGoodsTypeList(params)
    if (res.success) {
      goodsTypeOptions.value = Array.isArray(res.data) ? res.data : res.data.list || []
    }
  } catch (error) {
    logger.error('搜索商品类别失败', error)
  } finally {
    goodsTypeLoading.value = false
  }
}

// 修改商品介绍表单项，添加打开富文本的方法
const openRichTextEditor = () => {
  richTextContent.value = formData.value.introduce || ''
  richTextVisible.value = true
}

const handleRichTextConfirm = () => {
  formData.value.introduce = richTextContent.value
  richTextVisible.value = false
  formRef.value?.validateField('introduce')
}

// 查看HTML内容
const openHtmlPreview = () => {
  previewHtmlVisible.value = true
}

onMounted(async () => {
  try {
    // 获取行政区划数据
    await handleFetchXzqhTree()

    // 如果有初始数据，填充表单
    if (props.initialData) {
      formData.value = { ...formData.value, ...props.initialData }
      formData.value.cdXzqhId =
        props.initialData.cdXzqhId ?? props.initialData.dealerGoodsXzqhId ?? ''
      if ('dealerGoodsXzqhId' in formData.value) {
        delete formData.value.dealerGoodsXzqhId
      }
      formData.value.isDiscontinued =
        typeof formData.value.isDiscontinued === 'number'
          ? formData.value.isDiscontinued
          : Number(formData.value.isDiscontinued) || 0

      // 初始化级联选择器
      if (xzqhTree.value && xzqhTree.value.length > 0) {
        setInitialXzqh()
      }
    }

    await remoteSearchGoodsTypes('')
  } catch (error) {
    logger.error('组件挂载时出错', error)
    // 捕获并记录任何在挂载阶段可能发生的错误
  }
})
</script>

<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" v-loading="loading">
    <el-row>
      <el-col :span="12">
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="formData.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="商品类别" prop="dealerGoodsTypeId">
          <el-select
            v-model="formData.dealerGoodsTypeId"
            placeholder="请选择商品类别"
            filterable
            remote
            :remote-method="remoteSearchGoodsTypes"
            :loading="goodsTypeLoading"
            clearable
          >
            <el-option
              v-for="item in goodsTypeOptions"
              :key="item.dealerGoodsTypeId"
              :label="item.dealerGoodsTypeName"
              :value="item.dealerGoodsTypeId"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="商品规格" prop="specifications">
          <el-input v-model="formData.specifications" placeholder="请输入商品规格" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="商品单位" prop="unit">
          <el-input v-model="formData.unit" placeholder="请输入商品单位" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="停售状态">
          <el-switch
            v-model="formData.isDiscontinued"
            :active-value="1"
            :inactive-value="0"
            active-text="停售"
            inactive-text="在售"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 积分消费区域-->
    <el-form-item label="积分消费区域" prop="cdXzqhId">
      <el-cascader
        v-model="selectedXzqh"
        :options="xzqhTree"
        :props="{
          expandTrigger: 'hover',
          checkStrictly: false,
          label: 'text',
          value: 'id',
          children: 'children',
          emitPath: true,
        }"
        placeholder="请选择积分消费区域"
        clearable
        filterable
        :loading="xzqhLoading"
        @change="handleXzqhChange"
        style="width: 100%"
      />
    </el-form-item>

    <!-- 详细产地独占一行 -->
    <el-form-item label="商品产地" prop="address">
      <el-input v-model="formData.address" placeholder="请输入详细产地" />
    </el-form-item>

    <el-form-item label="商品图片" prop="goodsPicture">
      <el-upload
        ref="uploadRef"
        class="goods-picture-uploader"
        :http-request="customUpload"
        :show-file-list="false"
        :before-upload="beforeUpload"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :limit="1"
      >
        <div v-if="formData.goodsPicture" class="uploaded-image-container">
          <el-image :src="formData.goodsPicture" class="uploaded-image" fit="cover" />
          <div class="image-delete-mask" @click.stop="clearUploadedImage">
            <el-icon class="delete-icon"><LineMdTrash /></el-icon>
          </div>
        </div>
        <div v-else-if="uploadLoading" class="upload-placeholder">
          <el-icon class="loading-icon"><LineMdUploadingLoop /></el-icon>
          <span>上传中...</span>
        </div>
        <div v-else class="upload-placeholder">
          <el-icon><LineMdPlus /></el-icon>
          <span>点击上传图片</span>
        </div>
      </el-upload>
    </el-form-item>
    <el-form-item label="商品介绍" prop="introduce">
      <div class="rich-text-preview">
        <div class="content-actions">
          <span v-if="formData.introduce" class="content-status has-content">
            已填写内容
            <el-button type="text" @click="openHtmlPreview">
              <template #icon>
                <el-icon><LineMdWatchLoop /></el-icon>
              </template>
              查看内容
            </el-button>
          </span>
          <span v-else class="content-status no-content"> 暂无内容 </span>
          <el-button type="primary" @click="openRichTextEditor">
            <template #icon>
              <el-icon><LineMdEdit /></el-icon>
            </template>
            {{ formData.introduce ? '编辑内容' : '添加内容' }}
          </el-button>
        </div>
      </div>
    </el-form-item>
    <div class="dialog-footer">
      <el-button @click="emit('close')">
        <template #icon>
          <el-icon><LineMdClose /></el-icon>
        </template>
        取 消
      </el-button>
      <el-button type="primary" @click="handleSubmit">
        <template #icon>
          <el-icon><LineMdPlus /></el-icon>
        </template>
        确 定
      </el-button>
    </div>

    <!-- 富文本编辑器对话框 -->
    <el-dialog
      v-model="richTextVisible"
      title="编辑商品介绍"
      width="70%"
      destroy-on-close
      align-center
      :close-on-click-modal="false"
    >
      <RichTextEditor v-model="richTextContent" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="richTextVisible = false">
            <template #icon>
              <el-icon><LineMdClose /></el-icon>
            </template>
            取 消
          </el-button>
          <el-button type="primary" @click="handleRichTextConfirm">
            <template #icon>
              <el-icon><LineMdPlus /></el-icon>
            </template>
            确 定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看HTML内容对话框 -->
    <el-dialog
      align-center
      v-model="previewHtmlVisible"
      title="商品介绍预览"
      width="40%"
      destroy-on-close
    >
      <ViewHTML :content="formData.introduce" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewHtmlVisible = false">
            <template #icon>
              <el-icon><LineMdClose /></el-icon>
            </template>
            关 闭
          </el-button>
          <el-button type="primary" @click="openRichTextEditor">
            <template #icon>
              <el-icon><LineMdEdit /></el-icon>
            </template>
            编辑
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-form>
</template>

<style scoped>
.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

.goods-picture-uploader {
  width: 100%;
}

.uploaded-image {
  width: 200px;
  height: 200px;
  border-radius: 4px;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 200px;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-placeholder:hover {
  border-color: #409eff;
}

.upload-placeholder .el-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 8px;
}

.loading-icon {
  animation: loading-rotate 2s linear infinite;
}

@keyframes loading-rotate {
  100% {
    transform: rotate(360deg);
  }
}

.rich-text-preview {
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  padding: 12px;
  background-color: #f8f8f8;
}

.content-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
}

.content-status {
  display: flex;
  align-items: center;
  gap: 10px;
}

.has-content {
  color: #409eff;
}

.no-content {
  color: #909399;
  font-style: italic;
}

.html-preview {
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  height: calc(100vh - 200px);
  overflow-y: auto;
  background-color: white;
}

.uploaded-image-container {
  position: relative;
  width: 200px;
  height: 200px;
}

.image-delete-mask {
  position: absolute;
  top: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 0 0 0 4px;
}

.delete-icon {
  color: white;
  font-size: 20px;
}
</style>
